<template>
  <!-- 郭亚山 迭代 2.1.0 -->
  <div class="item-right-title">
    <div class="name">{{ state.nodeName }}</div>
    <template v-if="props.checkType * 1 === 1 || props.checkType * 1 === 4">
      <span v-if="state.showApplyPerson.length > 1" class="select-texts"
        >全部{{ state.showApplyPerson.length }}人</span
      >
    </template>
    <template v-else
      ><span v-if="!props.fixed && state.addPerson.length > 1" class="select-texts"
        >全部{{ state.addPerson.length }}人</span
      ></template
    >
  </div>
  <div class="item-right-select" style="justify-content: flex-end">
    <div class="select-have">
      <template v-if="props.fixed === true">
        <!-- 指定成员 ，不展示加号-->
        <div v-if="state.showApplyPerson.length > 1" class="select-out">
          <span class="selectH" @click="state.showAllPerson = true">
            <span class="select-img">
              <img class="img-avatar" :src="state.imgDefault" alt="" />
            </span>
            <span class="select-text">查看全部</span>
          </span>
          <span class="add-symbol">
            <SymbolIcon symbol="+" />
          </span>
        </div>
        <div v-for="(i, index) in state.showApplyPerson" :key="i.id" class="select-out sss">
          <span v-if="index < 2" class="selectH">
            <span class="select-img">
              <img class="img-avatar" :src="i.avatar || state.imgAvatar" alt="" />
            </span>
            <span class="select-text">{{ i.username }}</span>
          </span>
          <span v-if="index < 1" class="add-symbol">
            <SymbolIcon :symbol="props.symbol" />
          </span>
        </div>
      </template>
      <template v-else>
        <!-- 非指定成员 -->
        <div v-if="state.addPerson.length > 1" class="select-out ww">
          <span class="selectH" @click="state.showAllPerson = true">
            <span class="select-img">
              <img class="img-avatar" :src="state.imgDefault" alt="" />
            </span>
            <span class="select-text">查看全部</span>
          </span>
          <span class="add-symbol">
            <SymbolIcon symbol="+" />
          </span>
        </div>
        <div v-for="(item, index) in state.addPerson" :key="index" class="select-out gg">
          <span v-if="index < 1" class="selectH">
            <span class="select-img">
              <img class="img-avatar" :src="item.avatar || state.imgAvatar" alt="" />
              <icon
                v-if="index < 1"
                class="select-remove"
                size="15px"
                @click="onDeletePerson(state.addPerson, index)"
              >
                <img src="@/assets/img/icon_delete.png" style="width: 14px" alt="" />
              </icon>
            </span>
            <span class="select-text">{{ item.realName }}</span>
          </span>

          <!-- 非指定人员只选择一人，选择一人后连接号不展示 -->
          <span v-if="peopleIsMultiple === true && index < 1" class="add-symbol">
            <SymbolIcon :symbol="props.symbol" />
          </span>
        </div>
      </template>
      <template v-if="props.fixed === false">
        <!--加号 非指定成员 多选-->
        <div v-if="peopleIsMultiple" class="select-out select-no">
          <span class="selectP" @click="selectPeopleFn(index)">
            <span class="self-star">*</span>
            <icon class="avatar-select-icon">
              <SymbolIcon symbol="+" color="primary" />
            </icon>
          </span>
        </div>
        <!--加号 非指定成员 单选-->
        <div v-else class="select-out select-no">
          <span
            v-if="getResultData?.people.length < 1"
            class="selectP"
            @click="selectPeopleFn(index, 'only')"
          >
            <span class="self-star">*</span>
            <icon class="avatar-select-icon">
              <SymbolIcon symbol="+" color="primary" />
            </icon>
          </span>
        </div>
      </template>
    </div>
  </div>
  <!-- 指定人员展示使用，选择人员展示  大于6人样式-->
  <a-modal
    title="查看全部"
    :visible="state.showAllPerson"
    width="470px"
    :destroy-on-close="true"
    @cancel="state.showAllPerson = false"
    @ok="state.showAllPerson = false"
  >
    <template #header>
      <div class="add-title">
        <span class="close">
          <icon size="20px" @click="state.showAllPerson = false"><close /></icon>
        </span>
      </div>
    </template>
    <div class="self-body-warp">
      <span class="self-sub-title">
        审批人共
        {{ props.fixed === true ? state.showApplyPerson.length : state.addPerson.length }}人
      </span>
      <div class="item-right-selects" style="margin-top: 12px; justify-content: flex-start">
        <div class="select-haves">
          <template v-if="props.fixed === true">
            <!-- 指定成员 ，不展示加号-->
            <div v-for="(i, j) in state.showApplyPerson" :key="i.id" class="select-out">
              <span class="selectH">
                <span class="select-img">
                  <img class="img-avatar" :src="i.avatar || state.imgAvatar" alt=""
                /></span>
                <span class="select-text">{{ i.username }}</span>
              </span>
              <span v-if="(j + 1) % 6 !== 0" class="add-symbol">
                <SymbolIcon :symbol="props.symbol" />
              </span>
            </div>
          </template>
          <template v-else>
            <!-- 非指定成员 -->
            <!--加号 非指定成员 多选-->
            <div v-if="peopleIsMultiple" class="select-out select-no">
              <span class="selectP" @click="selectPeopleFn(index)">
                <span class="self-star">*</span>
                <icon class="avatar-select-icon">
                  <SymbolIcon symbol="+" color="primary" />
                </icon>
              </span>
              <span v-if="peopleIsMultiple === true" class="add-symbol">
                <SymbolIcon symbol="+" />
              </span>
            </div>
            <div v-for="(item, index) in state.addPerson" :key="index" class="select-out">
              <span class="selectH">
                <span class="select-img">
                  <img class="img-avatar" :src="item.avatar || state.imgAvatar" alt="" />
                  <icon
                    class="select-remove"
                    size="15px"
                    @click="onDeletePerson(state.addPerson, index)"
                  >
                    <img src="@/assets/img/icon_delete.png" style="width: 14px" alt="" />
                  </icon>
                </span>
                <span class="select-text">{{ item.realName }}</span>
              </span>

              <!-- 非指定人员只选择一人，选择一人后连接号不展示 -->
              <span v-if="peopleIsMultiple === true" class="add-symbol">
                <SymbolIcon :symbol="props.symbol" />
              </span>
            </div>
          </template>
        </div>
      </div>
    </div>
  </a-modal>
  <!-- 组织架构选择审批人弹框 -- 选人  -->
  <MyPickProple
    v-if="state.showPupopStruct"
    v-model:visible="state.showPupopStruct"
    :max-count="maxCount"
    :appoint-state="appointState"
    :role-lists="roleList"
    :contacts-list="contactsList"
    :type="'people'"
    :echo-data="getResultData.people"
    @onOK="updateMember"
  ></MyPickProple>
</template>
<script setup>
import { ref, reactive, defineProps, defineEmits, watchEffect, provide } from 'vue';
// import { Plus, Close } from '@element-plus/icons-vue';
import SymbolIcon from '@/components/base/symbolIcon.vue';
import MyPickProple from '@/components/pickProple/index.vue';
import { TjPickAndGroup } from 'tj-design-vue';
import {
  getDeptTree,
  getRelationSchoolRoleStruct,
  getFrequentContacts,
  saveFrequentContacts
} from '@/api/receiveDetails';
import store from '@/store';
const props = defineProps({
  title: String,
  index: String,
  isPeople: {
    // 是否使用【部门架构组件】选择人员还是【指定人员组件】选择人员，true显示纯人员选择组件，false部门架构人员组件
    type: Boolean,
    default: false
  },
  checkType: String,
  people: {
    // 指定人员展示数组，传过来的指定人员数组
    type: Array,
    default: () => []
  },
  selectPeople: {
    // 用于可以选择人的数组
    type: Array,
    default: () => []
  },
  peopleIsMultiple: {
    // 【部门架构组件】【指定人员组件】单选还是多选 true默认多选
    type: Boolean,
    default: true
  },
  fixed: {
    // 是否是指定人员还是自选人员 true只显示指定人员，不展示加号，false不显示指定人员，展示加号
    type: Boolean,
    default: false
  },
  resultProp: {
    // 用于回显选择传入的人员
    type: Array,
    default: () => []
  },
  symbol: {
    // 人员连接符号
    type: String,
    default: ''
  },
  // 在流程图中位置
  nodeId: {
    type: String,
    default: ''
  }
});
let emit = defineEmits(['toResult', 'toReturnPeople']);
const state = reactive({
  imgDefault: require('@/assets/img/oa_icon_quanburenyuan@2x.png'),
  imgAvatar: require('@/assets/img/oa-img-default.png'),
  nodeName: props.title, // 审批人
  showPupopStruct: false, // 选择弹框
  showApplyPerson: [], // 后台传入人员数组
  addPerson: [], // 自选人员数组
  showAllPerson: false // 展示全部审批人的弹框
});
const getResultData = ref({});
watchEffect(() => {
  if (props.fixed) {
    if (props.people && props.people.length !== 0) {
      let getpropper = props.people;

      let getNewPersonProp = getpropper.map(item => {
        item['userId'] = item.id;
        return item;
      });

      state.showApplyPerson = getNewPersonProp;
    }
  }
  let data = {
    people: props.fixed ? state.showApplyPerson : state.addPerson,
    nodeId: props.nodeId
  };
  getResultData.value = data;
  emit('toResult', data);
});
// 删除自选人员
let onDeletePerson = (ary, index) => {
  ary.splice(index, 1);
  let data = {
    people: state.addPerson,
    nodeId: props.nodeId
  };
  getResultData.value = data;
  emit('toReturnPeople', state.addPerson.length === 0 ? [] : getResultData.value, props.index);
};
const appointState = ref(false); // 是否是指定人员状态
const contactsList = ref([]); // 常用联系人
const roleList = ref([]); // 角色数组
// 打开人员选择
let maxCount = ref('不限');
async function selectPeopleFn(index, type) {
  if (props?.selectPeople.length > 0) {
    appointState.value = true;
    // 指定选择某些人（如果指定成员不需要常用联系人以及角色， 组织）
    let allPeoples = []; // 所有人
    props.selectPeople.forEach(item => {
      allPeoples.push({
        userId: item.id,
        userName: item.username,
        avatar: item.avatar,
        mobile: item.mobile,
        schoolId: item.schoolId,
        tenantId: item.tenantId,
        deptName: item.deptName,
        username: item.username
      });
    });
    let data = [
      {
        id: '888',
        name: '选择指定人员',
        childList: [{ id: '7777', name: '选择指定人员', teacherList: allPeoples }],
        tenantId: '9999',
        schoolId: '999'
      }
    ];
    roleList.value = data; // 指定人员固定架构
    store.commit('user/roleList', data); // 指定人员固定架构
    // state.showPupopStruct = true; // 打开选人弹窗
  } else {
    appointState.value = false;
    // 角色接口
    await getRelationSchoolRoleStruct({}).then(res => {
      if (res.code * 1 === 200) {
        let data = res.data;
        console.log('角色接口', data);
        roleList.value = data;
        store.commit('user/roleList', data); // 指定人员固定架构
      }
    });
    // 常用联系人
    await getFrequentContacts({}).then(res => {
      if (res.code * 1 === 200) {
        res.data.forEach(item => {
          item.userId = item.contactsUserId;
        });
        contactsList.value = res.data;
        provide('contactsListq', contactsList.value);
        store.commit('user/contactsList', contactsList.value);
      }
    });
  }
  // 组织结构接口
  await getDeptTree({}).then(res => {
    if (res.code * 1 === 200) {
      let allPeoples = []; // 所有人
      let peopleLists = []; // 所有人
      res.data.forEach(item => {
        item.listPeople.forEach(it => {
          peopleLists.push({ ...it });
        });
      });
      if (props?.selectPeople.length > 0) {
        // 指定人员没有手机号跟组织， 需要去组织架构中去匹配
        peopleLists.forEach(item => {
          props?.selectPeople.forEach(it => {
            if (item.userId === it.id) {
              allPeoples.push({
                userId: it.id,
                userName: item.userName, // 用户中心返回有区别
                avatar: item.avatar,
                deptName: item.deptName, // 职位
                mobile: item.mobile, // 手机号
                ...it
              });
            }
          });
        });
      } else {
        allPeoples = peopleLists;
      }
      console.log(56666, getResultData.value.people);
      state.showPupopStruct = true; // 打开选人弹窗
      // console.log(allPeoples);
      let allPeople = allPeoples.reduce((acc, curr) => {
        let existingItem = acc.find(item => item.userId === curr.userId);
        if (existingItem) {
          existingItem.deptName += `，${curr.deptName}`;
        } else {
          acc.push({ ...curr });
        }
        return acc;
      }, []);
      allPeople.forEach(item => {
        item.username = item.userName;
      });
      // console.log(allPeople, '所有人');
      res.data.forEach(item => {
        item.categoryId = item.schoolBusinessId;
      });
      // console.log(res.data, '组织结构数据');

      store.commit('user/departmentDatas', res.data);
      store.commit('user/allPeoples', allPeople);
      if (type === 'only') {
        // 只能选一个
        maxCount.value = 1;
      } else {
        maxCount.value = allPeople.length;
      }
    }
  });
}

function traverse(tree) {
  tree.childList.forEach(child => {
    if (child.childList.length > 0) {
      traverse(child);
    }
  });
}
function updateMember(val) {
  console.log('参数', val);
  let list = [];
  let params = [];
  val.forEach(item => {
    params.push({
      contactsUserId: item.userId,
      schoolId: item.schoolId || item.schoolBusinessId,
      tenantId: item.tenantId
    });
    list.push({
      // 这里会有多个重复字段 有的是给组件用 有的给接口用
      realName: item.username,
      id: item.userId,
      icon: item.icon,
      avatar: item.avatar,
      username: item.username,
      userName: item.username,
      userId: item.userId,
      schoolId: item.schoolId || item.schoolBusinessId,
      tenantId: item.tenantId
    });
  });
  // console.log(333, params);
  saveFrequentContacts(params).then(res => {
    console.log(res);
  });
  // console.log(list);
  state.addPerson = list;
  state.showApplyPerson = list;
  getResultData.value = {
    people: state.addPerson,
    nodeId: props.nodeId
  };
  state.showPupopStruct = false;
  console.log(44444, getResultData.value, props.index);
  emit('toReturnPeople', getResultData.value, props.index);
}
// 人员选择去重
function uniqueArr(array) {
  let r = [];
  for (let i = 0, l = array.length; i < l; i++) {
    for (let j = i + 1; j < l; j++) {
      if (array[i].userId === array[j].userId) j = ++i;
    }
    r.push(array[i]);
  }
  return r;
}
</script>
<style lang="less" scoped>
@import '../style/addFlowPerson.less';
.tjs-box {
  z-index: 2023 !important;
}
.select-texts {
  font-size: 14px;
  font-family: Source Han Sans CN, Source Han Sans CN-Regular;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.4);
}
</style>
